package com.commerceE.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.domain.Category;
import com.commerceE.domain.Products;
import com.commerceE.domain.User;
import com.commerceE.service.CategoryService;
import com.commerceE.service.ProductService;
import com.commerceE.service.UserService;
import com.commerceE.util.MD5Util;

@SessionAttributes({"currentUser"})
@Controller
@RequestMapping("/account")
public class UserController {
	
	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);
	
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private UserService userService;
	
	@ModelAttribute("currentUser")
	public User initCurrentUser(Model model) {
		Object user = RequestContextHolder.currentRequestAttributes().getAttribute("currentUser", RequestAttributes.SCOPE_SESSION);
		if(user!=null){
			return (User)user;
		}else{
		    return User.createInitalUser(); 
		}
    }

	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String account(@ModelAttribute("currentUser")User currentUser, Model model) {
		logger.info("Welcome home!");
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		if(!User.validateCurrentUser(currentUser)){
			return "home";
		}
		return "account";
	}
	
	@RequestMapping(value = "/forgetPassword", method = RequestMethod.GET)
	public String forgetPassword(@ModelAttribute("currentUser")User currentUser,Model model) {
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		
		if(!User.validateCurrentUser(currentUser)){
			return "home";
		}
		return "forgetPassword";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(@ModelAttribute("currentUser")User currentUser, Model model) {
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		if(User.validateCurrentUser(currentUser)){
			return "home";
		}
		model.addAttribute("user",new User());
		return "login";
	}
	
	private static String LOGIN_RETURN = "login";
	
	@RequestMapping(value = "/loginSubmit", method = RequestMethod.POST)
	public String loginSubmit(User user, BindingResult result, String routeTo, @ModelAttribute("currentUser")User currentUser, Model model) {
		
		if(StringUtils.isBlank(routeTo)){
			routeTo = "/home.html";
		}
		if(currentUser!=null && currentUser.getUserid()!=null && currentUser.getUserid()!=0){
			return "redirect:" + routeTo;
		}
		if(User.validateCurrentUser(currentUser)){
			return "home";
		}
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		if(user!=null){
			if(StringUtils.isBlank(user.getUsername())){
				result.reject("error", "用户名不能为空.");
				return LOGIN_RETURN;
			}else if(StringUtils.isBlank(user.getPassword()) || user.getPassword().length()<6){
				result.reject("error", "密码不能为空 .");
				return LOGIN_RETURN;
			}
		}else{
			result.reject("error", "错误的用户名称或密码.");
			return LOGIN_RETURN;
		}
		User tempUser = userService.getUserByUsernameAndPassword(user.getUsername(), MD5Util.getMD5(user.getPassword()));
		if(tempUser==null || tempUser.getUserid()==null){
			result.reject("error", "错误的用户名称或密码.");
			return LOGIN_RETURN;
		}
		tempUser.setProductInstanceListOfSession(currentUser.getProductInstanceListOfSession());
		tempUser.setTotalPrice(currentUser.getTotalPrice());
		tempUser.setTotalQuantity(currentUser.getTotalQuantity());
		model.addAttribute("currentUser",tempUser);
		return "redirect:" + routeTo;
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(User user, BindingResult result, String routeTo, @ModelAttribute("currentUser")User currentUser, Model model) {
		if(StringUtils.isBlank(routeTo)){
			routeTo = "/home.html";
		}
		model.addAttribute("currentUser",new User());
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "redirect:" + routeTo;
	}
	
	
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(@ModelAttribute("currentUser")User currentUser, Model model) {
		if(currentUser==null){
			model.addAttribute("currentUser",User.createInitalUser());
		}
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("user",new User());
		model.addAttribute("featuredProductList",featuredProductList);
		return "register";
	}
	
	@RequestMapping(value = "/checkUserNameAvailability", method = RequestMethod.POST)
	public @ResponseBody String checkUserNameAvailability(String username){
		if(StringUtils.isBlank(username)){
			return "false";
		}else{
			if(userService.checkUserNameAvailability(username)){
				return "true";
			}else{
				return "false";
			}
		}
	}
	
	public static String REGISTER_RETURN = "register";
	
	@RequestMapping(value = "/registerSubmit", method = RequestMethod.POST)
	public String registerSubmit(User user, BindingResult result, Model model) {
		if(user!=null){
			if(StringUtils.isBlank(user.getUsername())){
				result.reject("error", "Username can't be null.");
				return REGISTER_RETURN;
			}else if(StringUtils.isBlank(user.getPassword()) || user.getPassword().length()<6){
				result.reject("error", "Password can't be null and length of password must be longer than 6.");
				return REGISTER_RETURN;
			}else if(StringUtils.isBlank(user.getEmail())){
				result.reject("error", "Email can't be null.");
				return REGISTER_RETURN;
			}
			if(!userService.checkUserNameAvailability(user.getUsername())){
				result.reject("error", "The username:"+user.getUsername() +" has been used.");
				return REGISTER_RETURN;
			}else if(!userService.checkEmailAvailability(user.getEmail())){
				result.reject("error", "The email:"+user.getEmail() +" has been used.");
				return REGISTER_RETURN;
			}
			user.setPassword(MD5Util.getMD5(user.getPassword()));
			user.setCreatedtime(new Date());
			userService.insertUser(user);
		}else{
			result.reject("User must not be null", "User must not be null.");
			return REGISTER_RETURN;
		}
		List<Category> categoryList = null;
		List<Products> featuredProductList = null;
		try {
			categoryList = categoryService.getAllListOfCategory();
			featuredProductList = productService.getProductListWithImage();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		model.addAttribute("categoryList",categoryList);
		model.addAttribute("featuredProductList",featuredProductList);
		return "registerSuccess";
	}
	
	//setter and getter
	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	
}
